<?php
/*
Name: Simple Polls
Description: Allows the author of a site to add polls on their Pages
Version: 1.0
Author: Julian Castaneda (Square IT Solutions)
Author URI: http://www.squareitsol.com/
*/
define("GSP_VERSION", '1.0');

define("GSP_PLUGINID", 'squareit-polls');
define("GSP_FOLDERPATH", GSPLUGINPATH . GSP_PLUGINID . '/');
define("GSP_DATAPATH", GSP_FOLDERPATH . 'data/');
define("GSP_LANGPATH", GSP_FOLDERPATH . 'lang/');
define("GSP_INCPATH", GSP_FOLDERPATH . 'inc/');
define("GSP_RELFOLDERPATH", substr(GSPLUGINPATH, strlen(GSROOTPATH)) . GSP_PLUGINID . '/');

//includes
require_once GSP_INCPATH.'common.inc.php';
require_once GSP_INCPATH.'functions.inc.php';


if(!isset($_SESSION)){session_start();}

//load settings
squareit_gsp_load_settings();

//LANGUAGE SUPPORT
require_once GSP_LANGPATH.$_SESSION['SQR_GSP']['language'].'.php';


# register plugin
register_plugin(
	GSP_PLUGINID,
	'Simple Polls',
	'1.0',
	'Square IT Solutions',
	'http://www.squareitsol.com/',
	'Description: Allows the author of a site add polls on their Pages',
	'plugins', //page type
	'squareit_setup_polls'
);

# hooks
if (file_exists(GSPLUGINPATH.'squareit-loadtab.php'))
{
	//hooks using tab loader
	add_action(GSP_PLUGINID.'-sidebar','sqr_createSideMenu',array(GSP_PLUGINID, GSP_PLUGINID,'Polls Manager'));
	add_action(GSP_PLUGINID.'-sidebar','sqr_createSideMenu',array(GSP_PLUGINID,'squareit_admin_add_new_poll','Add New Poll'));
	add_action('nav-tab','sqr_createNavTab',array(GSP_PLUGINID,'Polls'));
}
else
{
	add_action('plugins-sidebar','createSideMenu',array(GSP_PLUGINID,'Polls Manager'));
	//add_action('plugins-sidebar','createSideMenu',array(GSP_PLUGINID,'squareit_admin_add_new_poll','Add New Poll'));
}


add_filter('content','squareit_display_poll'); 
add_action('theme-header','squareit_poll_frontend_css',array());

/**
 * creates the settings page for the ReTweet Button
 */
function squareit_setup_polls()
{
	global $i18n;
        global $SESSIONHASH;
        
	$plugin_folder_path = GSPLUGINPATH.'squareit-polls/';

	//check for tab loader plugin
	if (!file_exists(GSPLUGINPATH.'squareit-loadtab.php'))
	{
		squareit_msg_box($i18n['SQR_ADMIN_TAB_MISSING']);
	}
	
	squareit_health_check($plugin_folder_path);
	
	//display messages passed by url
	if(isset($_GET['msg']))
	{
		squareit_msg_box($_GET['msg']);
	}
	
	?>
	<link rel="stylesheet" type="text/css" href="../<?php echo GSP_RELFOLDERPATH;?>css/jalert.css" media="all">
	<script type="text/javascript" src="../<?php echo GSP_RELFOLDERPATH;?>js/jquery.jalert.js"></script>
	
	<label>Square It's Simple Polls:</label><br/><br/>
	
	<p style="color:#8C8C8C">
		To display a poll in a page, just copy the code given (ie. <i>{squareit_poll_4bb104e22f23c}</i>) and paste it into the content. You can put multiple polls in the same page.
	</p>
	
	<?php
	$pagesArray = squareit_get_all_polls();
	$table = '';
	$counter = "0";
	if (count($pagesArray) != 0) 
	{ ?>
		<table class="edittable highlight paginate">
		<thead>
			<tr>
				<th>Poll Question</th>
				<th>Code</th>
				<th> </th>
			</tr>
		</thead>
		<?php
		foreach ($pagesArray as $page) 
		{	
			$counter++;
							
			$table .= '<tr id="tr-'.$page['poll_id'] .'" >';
			$table .= '<td><strong>'. cl($page['poll_question']) .'</strong></td>';
			$table .= '<td>{squareit_poll_'.$page['poll_id'].'}</td>';
			//$table .= '<td>[<a href="loadtab.php?id='.GSP_PLUGINID.'&item=squareit_admin_view_poll&pollid='.$page['poll_id'] .'#pollform">view results</a>]</td>';
			$table .= '<td class="delete"><a class="delconfirm" href="../'.GSP_RELFOLDERPATH.'deletepoll.php?ref='.GSP_PLUGINID.'&pid='.$page['poll_id'].'&s='.$SESSIONHASH.'" title="Are you sure you want to delete this poll?" >X</a></td></tr>';
						
		}
		echo $table;
		?>
		</table>
		<script>
		$('body').bind("ajaxComplete", function(event, xhr, options){
			//console.log('myVar: ', $.httpData(xhr,options.dataType)); 
	   		$('.main').jAlert('Poll Deleted Successfully', "success");
	 	});
	 	</script>
	<?php
	}else 
	{
		squareit_msg_box('<div style="font-size:14px">You don\'t have any polls yet! <br/>Create a <a href="loadtab.php?id='.GSP_PLUGINID.'&item=squareit_admin_add_new_poll">new poll</a> now. It\'s Simple!</div>');
	}
}

/**
 * Interface to add a new poll
 */
function squareit_admin_add_new_poll()
{
	$plugin_folder_path = GSPLUGINPATH.'squareit-polls/';
	
	$sqr_poll_question = '';
	$sqr_poll_answer1 = '';
	$sqr_poll_answer2 = '';
	$sqr_poll_answer3 = '';
	$sqr_poll_answer4 = '';
	$sqr_poll_answer5 = '';
	
	//handle post submission
	if (isset($_POST['submit'])) {
		$xml = @new SimpleXMLExtended('<?xml version="1.0" encoding="UTF-8"?><item></item>');
		
		$valid = true;
		if (trim($_POST['sqr_poll_question']) == '')
		{
			squareit_msg_box('Please enter a Poll Question!');
			$valid = false;
		}
		$note = $xml->addChild('poll_question');
		$sqr_poll_question = $_POST['sqr_poll_question'];
		$note->addCData($sqr_poll_question);
		
		$count = 0;
		//dynamic parsing of the needed fields
		foreach ($_POST as $fkey => $fval) {
			if(substr($fkey, 0, 4) == 'sqr_')
			{
				$fName = substr($fkey, 4);
				if (strpos($fName,'poll_answer') !== false && trim($fval) != '')
				{
					$count++;
					$sqr_poll_answer{$count} = $fval;
					$note = $xml->addChild($fName);
					$note->addCData($fval);
					$voteN = $note->addChild('votes');
					$voteN->addCData(0);
				}
			}
		}
		$uid = uniqid(); //generate a unique id for new poll
		$note = $xml->addChild('poll_id');
		$note->addCData($uid);

		if ($valid)
		{
			$xml->asXML($plugin_folder_path.$uid.".xml");
			//squareit_msg_box('Poll Saved Successfully!');
			header('location: loadtab.php?id='.GSP_PLUGINID.'&item='.GSP_PLUGINID.'&msg=Poll Saved Successfully!');
		}

	}

	?>
	<label>Create New Poll</label>
	<br/>
	<br/>
	<form method="post" action="<?php echo $_SERVER ['REQUEST_URI']?>">
		<table class="cleantable">
			<tr>
				<td style="width:25%" ><b>Poll Question?</b></td>
				<td>
					<input type="text" id="sqr_poll_question" name="sqr_poll_question" class="text" style="width:250px;" value="<?php echo $sqr_poll_question; ?>" />
				</td>
				
			</tr>
			<tr><td colspan="2" style="background-color:#F0F0F0"> </td></tr>
			<tr><td colspan="2">
			<table class="edittable highlight paginate">
			<?php
			for ($i=1; $i<=5; $i++)
			{?>
			<tr>
				<td style="width:25%" ><b>Answer #<?php echo $i;?></b></td>
				<td>
					<input type="text" name="sqr_poll_answer<?php echo $i;?>" class="text" style="width:250px;" value="<?php echo ${'sqr_poll_answer'.$i}; ?>" />
				</td>
			</tr>
			<?php }?>
			</table>
			</td></tr>
			
			<tr>
				<td>&nbsp;</td>
				<td><input type="submit" name="submit" class="submit" value="Save Poll" /> 
			</tr>
		</table>
	</form>
	<?php 
}

/**
 * Puts the actual poll in the content page
 * 
 * {squareit_poll_i42342342d}
 */
function squareit_display_poll($content)
{
	$plugin_folder_path = GSPLUGINPATH.'squareit-polls/';
	
	$found = preg_match_all('/\{squareit_poll_(\w+)\}/', $content, $match);
	
	for ($i=0; $i<=$found; $i++)
	{
		$pollid = '';
		if (isset($match[1][$i]))
		{
			$pollid = $match[1][$i];
		}
		else
		{
			return $content;
		}
		
		$poll = '';
		
		$sqr_poll_question = '';
		$sqr_poll_answer1 = '';
		$sqr_poll_answer2 = '';
		$sqr_poll_answer3 = '';
		$sqr_poll_answer4 = '';
		$sqr_poll_answer5 = '';
		$showResults = false;
		$result = false;
		if (file_exists($plugin_folder_path.$pollid.'.xml')) 
		{
			$v = getXML($plugin_folder_path.$pollid.'.xml');
				
			if (!isset($_COOKIE['squareit_poll_'.$pollid])) {
				$result = squareit_process_poll_vote($v);
			}
			else
			{
				$showResults = true;
			}
				
			//reassign returned xml by the proccess function
			if ($result)
			{
				$v = $result;
			}
			
			if (isset($_GET['spresult']))
			{
				$showResults = true;
			}
				
			$sqr_poll_question = $v->poll_question;
			$sqr_poll_answer1 = $v->poll_answer1;
			$sqr_poll_answer2 = $v->poll_answer2;
			$sqr_poll_answer3 = @$v->poll_answer3;
			$sqr_poll_answer4 = @$v->poll_answer4;
			$sqr_poll_answer5 = @$v->poll_answer5;
			
			$poll .= '<form method="post" action=""><input type="hidden" name="poll_id" value="'.$pollid.'" />';
			$poll .= '<table id="sqr_poll_'.$pollid.'" class="sqr_poll">';
			$poll .= '<tr><th colspan="2">'.$sqr_poll_question.'</th></tr>';

			if ($result || $showResults)
			{
				$poll .= squareit_display_poll_results($v);
			}
			else
			{
				$poll .= '<tr><td>'.$sqr_poll_answer1.'</td><td><input type="radio" name="sqr_poll_answer" value="1" /></td></tr>';
				$poll .= '<tr><td>'.$sqr_poll_answer2.'</td><td><input type="radio" name="sqr_poll_answer" value="2" /></td></tr>';
				if (isset($v->poll_answer3))
				{
					$poll .= '<tr><td>'.$sqr_poll_answer3.'</td><td><input type="radio" name="sqr_poll_answer" value="3" /></td></tr>';
				}
				if (isset($v->poll_answer4))
				{
					$poll .= '<tr><td>'.$sqr_poll_answer4.'</td><td><input type="radio" name="sqr_poll_answer" value="4" /></td></tr>';
				}
				if (isset($v->poll_answer5))
				{
					$poll .= '<tr><td>'.$sqr_poll_answer5.'</td><td><input type="radio" name="sqr_poll_answer" value="5" /></td></tr>';
				}
				
				//generate uri for the view result
				if (
					(isset($_SERVER['REDIRECT_QUERY_STRING']) && !$_SERVER['REDIRECT_QUERY_STRING'] == $_SERVER['QUERY_STRING']) // if using fancy urls
					 || 
					(!isset($_SERVER['REDIRECT_QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '')) //regular urls
				{
					//if any get params are available then append the spresult
					$viewURI = '?'.$_SERVER['QUERY_STRING'].'&spresult='.$pollid;
				}
				else {
					$viewURI = '?spresult='.$pollid;
				}
				
				$poll .= '<tr><td colspan="2" style="text-align:center"> <input type="submit" name="submit" value="submit" /> or 
				<a href="'.$viewURI.'">view results</a></td></tr>';
			}
			$poll .= '</table></form>';
			
		}
		else 
		{
			//poll not found. for now return the content. but in future return error message.
			$poll .= "<div style='color:red'><strong>Invalid POLL ID: $pollid</strong> <br/> Please check this poll exists.</div>";
		}
		$content = preg_replace('/\{squareit_poll_'.$pollid.'\}/', $poll, $content);
	}
	
	return $content;
}

function squareit_display_poll_results($pollXML)
{
	$totalVotes = 0;
	
	$totalVotes += $pollXML->poll_answer1->votes;
	$totalVotes += $pollXML->poll_answer2->votes;
	$totalVotes += @$pollXML->poll_answer3->votes;
	$totalVotes += @$pollXML->poll_answer4->votes;
	$totalVotes += @$pollXML->poll_answer5->votes;
	
	$opt1 = 0;
	$opt2 = 0;
	$opt3 = 0;
	$opt4 = 0;
	$opt5 = 0;
	
	//TODO make this dynamic
	if ($totalVotes != 0)
	{
		$opt1 = round(($pollXML->poll_answer1->votes/$totalVotes)*100);
		$opt2 = round(($pollXML->poll_answer2->votes/$totalVotes)*100);
		$opt3 = round(($pollXML->poll_answer3->votes/$totalVotes)*100);
		$opt4 = round(($pollXML->poll_answer4->votes/$totalVotes)*100);
		$opt5 = round(($pollXML->poll_answer5->votes/$totalVotes)*100);
	}
	$poll = '';
	//Build results
	for ($i=1; $i<6; $i++)
	{
		$pollN = 'poll_answer'.$i;
		$optN = 'opt'.$i;
		if (isset($pollXML->$pollN))
		{	
			$poll .= '
			<tr>
				<td nowrap="nowrap" colspan="2">
					'.$pollXML->$pollN.' <span class="sqr_poll_num_v">('.$$optN.'%, '.$pollXML->$pollN->votes.' votes)</span><br/>
					<div class="sqr_vote_per" style="width:'.$$optN.'%">&nbsp</div>
				</td>
			</tr>';
		}
		
	}
	
	return $poll;
}



/**
 * Get an array of all the pages currently available
 *
 * @return array
 */
function squareit_get_all_polls()
{
	$plugin_folder_path = GSPLUGINPATH.'squareit-polls/';
	$path = $plugin_folder_path;
	
	//display all pages
	$filenames = getFiles($path);
	$count="0";
	$pagesArray = array();
	if (count($filenames) != 0) { 
		foreach ($filenames as $file) {
			if (isFile($file, $path, 'xml')) {
				$data = getXML($path . $file);
				$pagesArray[$count]['poll_question'] = html_entity_decode($data->poll_question, ENT_QUOTES, 'UTF-8');
				$pagesArray[$count]['poll_id'] = $data->poll_id;
				
				$count++;
			}
		}
	}
	
	
	return $pagesArray;
}

function squareit_process_poll_vote($pollXML)
{
	//return false if no answer provided
	if (!isset($_POST['sqr_poll_answer']))
	{
		return false;
	}
	else if($_POST['sqr_poll_answer']==0)
	{
		return false;
	}
	
	//return false if no poll id was passed
	if (!isset($_POST['poll_id']) && trim($_POST['poll_id'])=='')
	{
		return false;
	}
	
	//return false if poll id does not match poll id from xml
	if ($_POST['poll_id'] != $pollXML->poll_id)
	{
		return false;
	}
	
	$pid = $_POST['poll_id'];
	
	if (!isset($_COOKIE['squareit_poll_'.$pid])) {
		$plugin_folder_path = GSPLUGINPATH.'squareit-polls/';
		
		//vote goes to...
		$vote = 'poll_answer'.$_POST['sqr_poll_answer'];
		//add new vote
		$currentNode = $pollXML->$vote->votes++;
		//save new vote
		$pollXML->asXML($plugin_folder_path.$pid.".xml");
		
		//save a cookie to prevent multiple submissions
		setcookie("squareit_poll_".$pid, $_SERVER['REMOTE_ADDR'], time()+86400);  /* expire in 24 hours */
	
		return $pollXML;
	}
	
	return false;
}

/**
 * Includes CSS for the polls to work
 */
function squareit_poll_frontend_css()
{
	global $SITEURL;
	?>
	<link rel="stylesheet" type="text/css" href="<?php echo $SITEURL.GSP_RELFOLDERPATH;?>css/poll.css" media="all">
	<?php 
}

/**
 *  Generates a message box
 *  - Prepare it so that it can be used across all square it plugins
 */
if (!function_exists('squareit_msg_box'))
{
	function squareit_msg_box($msg, $type='updated')
	{
		echo '<div class="'.$type.'"> 
				'.$msg.' 
			 </div>';
	}
}

/**
 * Checks to see if directory permission is set correctly
 */
if (!function_exists('squareit_health_check'))
{
	function squareit_health_check($dir_path)
	{
		$plugPerm = substr(base_convert(@fileperms($dir_path), 10, 8), 2);
		
		$plugFolder = str_replace('/', '', substr($dir_path, strlen(GSPLUGINPATH)));

		if ($plugPerm < 755 && !($plugPerm == '' || $plugPerm == 0))
		{
			$msg = $i18n['SQR_PERM_TO'].' <i><b>'.$plugFolder.'</b></i> '.$i18n['SQR_PERM_NOT_SET_MSG'].' <br/>';
			$msg .= '<b>'.$i18n['SQR_PERM_PATH'].':</b> '.$dir_path.'<br/>';
			$msg .= '<b>'.$i18n['SQR_PERM_CURRENT'].':</b> 0'.$plugPerm.'<br/>';
			$msg .= '<b>'.$i18n['SQR_PERM_RECOMMENDED'].':</b> 0755';
			
			squareit_msg_box($msg, 'error');
		} 
		else if($plugPerm == '' || $plugPerm == 0)
		{
			$msg = $i18n['SQR_PERM_NOT_EXISTS_MSG'].' <i><b>'.$plugFolder.'</b></i> '.$i18n['SQR_PERM_NOT_EXISTS_MSG_CONT'].'<br/>';
			$msg .= '<b>'.$i18n['SQR_PERM_PATH'].':</b> '.$dir_path.'<br/>';
			$msg .= '<b>'.$i18n['SQR_PERM_RECOMMENDED'].':</b> 0755';
			squareit_msg_box($msg, 'error');
		}
	}
}
